package com.example.controller;

import com.example.common.BarCodeUtils;
import com.example.common.Result;
import com.example.dao.StockDao;
import com.example.entity.Stock;
import com.example.service.StockService;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;

import static com.example.common.BarCodeUtils.getBarCode;
import static com.example.common.BarCodeUtils.insertWords;

@RestController
@RequestMapping("/stock")
public class StockController {

    @Resource
    private StockService stockService;

    @PostMapping
    public Result add(@RequestBody Stock stock) throws IOException {
        stock.setId(System.currentTimeMillis() / 1000);
        stockService.save(stock);
        String id = stock.getId().toString();
        String name = stock.getName();
        BufferedImage image = insertWords(getBarCode(id), name);
        try {
            ImageIO.write(image, "jpg", new File("D://abc.jpg"));
        }catch (IOException e){
            System.out.println("IO异常");
            Result.error("0","存储条形码图片异常");
        }
        return Result.success();
    }

    @PutMapping
    public Result update(@RequestBody Stock stock){
        stockService.save(stock);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public void del(@PathVariable("id") Long id) {
        stockService.del(id);
    }
    // 根据id查询货物
    @GetMapping("/{id}")
    public Result<Stock> findById(@PathVariable Long id) {
        return Result.success(stockService.findById(id));
    }

    // 查询所有货物
    @GetMapping
    public Result<List<Stock>> findAll() {
        return Result.success(stockService.findAll());
    }

    // 分页查询货物
    @GetMapping("/page")
    public Result<Page<Stock>> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                       @RequestParam(defaultValue = "50") Integer pageSize) {
        return Result.success(stockService.findPage(pageNum, pageSize));
    }

    //模糊查询--名称
    @GetMapping("/name")
    public Result<List<Stock>> findLikeName(@RequestParam(defaultValue = "") String name){
        return Result.success(stockService.findLikeName(name));
    }

    //模糊查询--生产厂家
    @GetMapping("/made")
    public Result<List<Stock>> findLikeFactory(@RequestParam(defaultValue = "") String made){
        return Result.success(stockService.findLikeFactory(made));
    }

    //模糊查询--供应商
    @GetMapping("/supplier")
    public Result<List<Stock>> findLikeSupplier(@RequestParam(defaultValue = "") String supplier){
        return Result.success(stockService.findLikeSupplier(supplier));
    }
}
